package DataStructure.stack;

import java.util.Arrays;

//顺序栈
public class SeqStack<E> implements MyStack<E>{
    private E[] e;//元素数组
    private int size;


    public SeqStack() {
        e= (E[]) new Object[4];
        size=0;
    }

    //扩充容量
    private void grow(){
        E[] tmp=e;
        e=(E[]) new Object[size*2];
        for (int i = 0; i < size; i++) {
            e[i]=tmp[i];
        }
    }
    //缩减容量
    private void cut(){

    }

    @Override
    public E peek() {
        if(isEmpty())
            return null;
        return e[size-1];
    }

    @Override
    public void push(E e) {
        if(size==this.e.length)
            grow();
        this.e[size++]=e;
    }

    @Override
    public E pop() {
        if(isEmpty())
            return null;
        return e[--size];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void clear() {
        e= (E[]) new Object[4];
        size=0;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            sb.append(e[i]);
            if(i!=size-1)
                sb.append(",");
        }
        sb.append("]");
        return "SeqStack{" +
                "e=" + sb +
                ", size=" + size +
                '}';
    }
}
